from web3 import Web3
import functools
import os
import json


@functools.lru_cache()
def _load_abi(name: str) -> str:
    path = "data/coin1//abi/uniswap_v2"
    with open(os.path.join(path, f"{name}.abi")) as f:
        abi: str = json.load(f)
    return abi


@functools.lru_cache()
def _load_contract(w3, abi_name: str, address):
    address = Web3.to_checksum_address(address)
    return w3.eth.contract(address=address, abi=_load_abi(abi_name))


@functools.lru_cache()
def _addr_to_str(a) -> str:
    if isinstance(a, bytes):
        # Address or ChecksumAddress
        addr: str = Web3.to_checksum_address("0x" + bytes(a).hex())
        return addr
    elif isinstance(a, str) and a.startswith("0x"):
        addr = Web3.to_checksum_address(a)
        return addr

    raise RuntimeError("name not found")
